﻿using AutoMapper;
using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Write.Applications.Commands.PackagingPlanCommands;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Write.Applications.CommandHandlers.PackagingPlanCommandHandlers
{
    public class AddPackagingPlanCommandHandlers : IRequestHandler<AddPackagingPlanCommands, APIResult<object>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper _mapper;

        public AddPackagingPlanCommandHandlers(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            _mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(AddPackagingPlanCommands request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.code = APIResultCode.success;
            result.msg = "包装计划添加成功";

            var model = _mapper.Map<PackagingPlan>(request);

            model.isload = 0;
            model.Preparation = false;
            model.Picking = false;
            // 使用 ExecuteReturnIdentityAsync 方法插入数据并返回自增主键
            int productionPlanningId = await db.Insertable(model).ExecuteReturnIdentityAsync();

            RecordsOperations records = new RecordsOperations();
            records.Operator = "王浩然";
            records.OperatingTime = DateTime.Now;
            records.OperationContent = "新增计划";

            await db.Insertable(records).ExecuteCommandAsync();

            // 将主键添加到结果中
            result.data = new { productionPlanningId };

            return await Task.FromResult(result);
        }
    }
}
